# 工具包

import os
import hashlib
from threading import Thread

from flask import current_app, render_template, request
from flask_mail import Message
from flask_login import current_user
from werkzeug.utils import secure_filename

from . import mail
from app.models import Post, Article



# 异步发送邮件
def send_async_email(app, msg):
    # 加入flask 上下文
    with app.app_context():
        mail.send(msg)  # 发送邮件


# 发送邮件
def send_email(user, subject: str, template: str, **kwargs):
    # 获取当前 app 对象
    app = current_app._get_current_object() 

    msg = Message(
        subject=app.config.get("MAIL_SUBJECT_PREFIX", "")+" "+subject,
        recipients=[user.email],
        sender=app.config.get("FLASKY_MAIL_SENDER"),
        html=render_template(template, user=user, subject=subject, **kwargs)
    )

    # 新开线程，发送邮件
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr


# 获取 用户post or article 计算可以分为多少页
def get_page_all(cls_, user=None):

    if user is None:
        user = current_user

    n = cls_.query.filter_by(user_id=user.id, deleted="false").count() / current_app.config.get("DEFAULT_PAGE_NUMBER", 10)
    
    # 非整数加1
    if str(n).split(".")[-1] != "0":
        n = int(n)+1
    return int(n)


# 获取 用户所有 post article 并分页
def get_user_post_article():
    page = request.args.get("page", 1, int)
    limit = current_app.config.get("DEFAULT_PAGE_NUMBER", 10) // 2
    offset = (page-1)*limit // 2

    a = Article.query.filter_by(draft="false", deleted="false", user_id=current_user.id) \
        .order_by(Article.created_time.desc()).offset(offset).limit(limit).all()

    p = Post.query.filter_by(deleted="false", user_id=current_user.id) \
        .order_by(Post.created_time.desc()).offset(offset).limit(limit).all()

    posts = a+p
    posts.sort(key=lambda k: k.created_time, reverse=True)

    return posts, page



# 获取 用户post or article 当前页的数据，返回数据和页码
def get_user(cls_, user=None):
    if user is None:
        user = current_user
        
    page = request.args.get("page", 1, int)
    limit = current_app.config.get("DEFAULT_PAGE_NUMBER", 10)
    offset = (page-1)*limit

    return cls_.query.filter_by(user_id=user.id, deleted="false") \
        .order_by(cls_.created_time.desc()).offset(offset).limit(limit).all(), page


# 保存图片
def save_user_img(past_name:str, img):
    path = os.path.join("app", "static", "imgs",
                        "user", past_name, str(current_user.id))
    if not os.path.isdir(path):
        os.makedirs(path)
    s = secure_filename(img.filename)
    f_name = hashlib.sha256(s.encode(encoding="utf-8")).hexdigest() + \
        os.path.splitext(s)[-1]
    img.save(os.path.join(path, f_name))

    s = "/" + os.path.join("static", "imgs", "user", past_name,
                        str(current_user.id), f_name)
    return s


# 检查图图片 url 是不是自己的
def check_img_url(url):
    u = ""
    if "static" in url: # 本站img utl 全部都在 static 下 
        i = url.index("static")
        u = url[i-1: ]
        return u, True
    return u, False